﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class AddLevaCommandHander : IRequestHandler<AddLevaCommand, ApiResult<int>>
    {
        public readonly IRepistory<LeaveApp> _levaRepository;
        public readonly IRepistory<User> _userRepository;
        public readonly IMapper _mapper;
        public AddLevaCommandHander(IRepistory<LeaveApp> levaRepository, IRepistory<User> userRepository, IMapper mapper)
        {
            _levaRepository = levaRepository;
            _userRepository = userRepository;
            _mapper = mapper;
        }
       
        public async Task<ApiResult<int>> Handle(AddLevaCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var m = _mapper.Map<LeaveApp>(request);
            m.CreateTime = DateTime.Now;
            m.StatusId = (int)Status.待审批;
            m.StatusName = Status.待审批.ToString();
            m.IsDeleted = false;
            //判断用户是领导/员工
            var u2 = _userRepository.GetAll().Where(x => x.UserId == request.LeaveId && x.PowerId == (int)PowerId.部门领导人).ToList();
            if (u2.Count() > 0)
            {
                //是
                var Ids = _userRepository.GetAll().Where(x => x.PowerId == (int)PowerId.总负责人).Select(x => x.UserId).ToList();
                m.LeaderIds = string.Join(",", Ids);
                var Names = _userRepository.GetAll().Where(x => x.PowerId == (int)PowerId.总负责人).Select(x => x.UserName).ToList();
                m.LeaderName = string.Join(",", Names);
                m.PowerId = (int)PowerId.部门领导人;

            }
            else
            {
                //否
                //通过部门Id和领导人查询到所有领导人的Ids
                var u = _userRepository.GetAll().Where(x => x.DepartmentId == request.DepartmentId && x.PowerId == (int)PowerId.部门领导人);
                var LIds = u.Select(x => x.UserId).ToList();
                m.LeaderIds = string.Join(",", LIds);
                var LNames = u.Select(x => x.UserName).ToList();
                m.LeaderName = string.Join(",", LNames);
                m.PowerId = (int)PowerId.员工;
            }
            var a = await _levaRepository.AddAsync(m);
            if (a > 0)
            {
                result.code = Renum.添加成功;
                result.Message = "添加成功";
                result.Data = a;
            }
            else
            {
                result.code = Renum.添加失败;
                result.Message = "添加失败";

            }
            return await Task.FromResult(result);
        }
    }
}
